#include "ConnectionManager.h"
#include "TcpConnection.h"
#include "block_log.h"
#include "ConnectPool.h"
#include "Connect.h"

ConnectionManager* ConnectionManager::s_instance = nullptr;

ConnectionManager* ConnectionManager::getInstance()
{
    if (s_instance == nullptr) {
        s_instance = new ConnectionManager();
    }
    return s_instance;
}

// 注册在线用户连接
void ConnectionManager::registerConnection(uint64_t userId, TcpConnection* conn)
{
    if (userId == 0 || conn == nullptr) {
        return;
    }
    
    std::lock_guard<std::mutex> lock(m_mutex);
    m_connections[userId] = conn;
    Debug("用户 %lu 连接已注册，当前在线用户数：%zu", userId, m_connections.size());
}

// 注销用户连接
void ConnectionManager::unregisterConnection(uint64_t userId)
{
    if (userId == 0) {
        return;
    }
    
    std::lock_guard<std::mutex> lock(m_mutex);
    auto it = m_connections.find(userId);
    if (it != m_connections.end()) {
        m_connections.erase(it);
        Debug("用户 %lu 连接已注销，当前在线用户数：%zu", userId, m_connections.size());
    }
}

// 查找在线用户连接
TcpConnection* ConnectionManager::getConnection(uint64_t userId)
{
    if (userId == 0) {
        return nullptr;
    }
    
    std::lock_guard<std::mutex> lock(m_mutex);
    auto it = m_connections.find(userId);
    if (it != m_connections.end()) {
        return it->second;
    }
    return nullptr;
}

// 检查用户是否在线（仅查内存）
bool ConnectionManager::isOnline(uint64_t userId)
{
    return getConnection(userId) != nullptr;
}

// 检查用户是否在线（带数据库回退）
bool ConnectionManager::isOnlineWithDbFallback(uint64_t userId, bool checkDb)
{
    // 优先查内存
    if (isOnline(userId)) {
        return true;
    }
    
    // 如果不需要查数据库，直接返回
    if (!checkDb) {
        return false;
    }
    
    // 查询数据库
    try {
        auto connPool = ConnectionPool::getConnectionPool();
        auto dbConn = connPool->getConnection();
        
        if (!dbConn) {
            Debug("获取数据库连接失败，无法查询用户在线状态");
            return false;
        }
        
        sql::Connection* conn = dbConn->getConnection();
        std::unique_ptr<sql::PreparedStatement> pstmt(
            conn->prepareStatement("SELECT status FROM users WHERE user_id = ?")
        );
        
        pstmt->setUInt64(1, userId);
        std::unique_ptr<sql::ResultSet> res(pstmt->executeQuery());
        
        if (res->next()) {
            int status = res->getInt("status");
            Debug("从数据库查询用户 %lu 状态：%d", userId, status);
            return status == 1;
        }
        
        return false;
        
    } catch (const sql::SQLException& e) {
        Debug("数据库查询用户状态异常: %s (错误码: %d)", e.what(), e.getErrorCode());
        return false;
    }
}

// 获取所有在线用户ID列表
std::vector<uint64_t> ConnectionManager::getOnlineUsers()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    std::vector<uint64_t> userIds;
    userIds.reserve(m_connections.size());
    
    for (const auto& pair : m_connections) {
        userIds.push_back(pair.first);
    }
    
    return userIds;
}

